﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace NpCrm.Domain
{
    public class User : NpCrmEntityBase
    {
        [Key]
        [DatabaseGenerated(DatabaseGenerationOption.Identity)]
        public int UserId { get; set; }

        //TODO: figure out a regex for this that works
        [Required(ErrorMessage = "Please enter a user name", AllowEmptyStrings = false)]
        [StringLength(20, ErrorMessage = "User name too long")]
        //[RegularExpression(@"^[a-zA-Z0-9]$", ErrorMessage = "User name can only contain alphanumeric characters, no special characters allowed.")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Please enter a password")]
        [StringLength(20, MinimumLength = 8, ErrorMessage = "Password must be at least 8 and no more than 20 characters")]
        [NotMapped]
        public string PlaintextPassword { get; set; }

        private string _password;
        [StringLength(100)]
        public string Password
        {
            get
            {
                if (String.IsNullOrEmpty(PlaintextPassword))
                    return _password;
                if(String.IsNullOrEmpty(_password))
                {
                    _password = BCrypt.HashPassword(PlaintextPassword, BCrypt.GenerateSalt());
                }
                return _password;
            }
            protected set { _password = value; }
        }

        [NotMapped]
        public bool IsAuthenticated { get; set; }

        public virtual ICollection<Role> Roles { get; set; }

        public User()
        {
            Roles = new HashSet<Role>();
        }

        public void Authenticate()
        {
            IsAuthenticated = BCrypt.CheckPassword(PlaintextPassword, _password);
        }

        public void Authenticate(string password)
        {
            PlaintextPassword = password;
            Authenticate();
        }

        
    }
}
